<?php

class Functions
{

    /**
     * [cutstr 汉字切割]
     * @param  [string] $string [需要切割的字符串]
     * @param  [string] $length [显示的长度]
     * @param  string $dot [切割后面显示的字符]
     * @return [string]         [切割后的字符串]
     */
    static function cutstr($string, $length, $dot = '...')
    {
        if (strlen($string) <= $length) {
            return $string;
        }
        $string = str_replace(array(
            '&amp;',
            '&quot;',
            '&lt;',
            '&gt;'
        ), array(
            '&',
            '"',
            '<',
            '>'
        ), $string);
        $strcut = '';
        $n = $tn = $noc = 0;
        while ($n < strlen($string)) {
            $t = ord($string[$n]);
            if ($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
                $tn = 1;
                $n++;
                $noc++;
            } elseif (194 <= $t && $t <= 223) {
                $tn = 2;
                $n += 2;
                $noc += 2;
            } elseif (224 <= $t && $t < 239) {
                $tn = 3;
                $n += 3;
                $noc += 2;
            } elseif (240 <= $t && $t <= 247) {
                $tn = 4;
                $n += 4;
                $noc += 2;
            } elseif (248 <= $t && $t <= 251) {
                $tn = 5;
                $n += 5;
                $noc += 2;
            } elseif ($t == 252 || $t == 253) {
                $tn = 6;
                $n += 6;
                $noc += 2;
            } else {
                $n++;
            }
            if ($noc >= $length) {
                break;
            }
        }
        if ($noc > $length) {
            $n -= $tn;
        }
        $strcut = substr($string, 0, $n);
        $strcut = str_replace(array(
            '&',
            '"',
            '<',
            '>'
        ), array(
            '&amp;',
            '&quot;',
            '&lt;',
            '&gt;'
        ), $strcut);
        return $strcut . $dot;
    }

    /**
     * [getPassedHours 某时间戳到现在所经过的时间]
     * @param  [int] $distence [时间戳]
     * @return [string]           [秒/分钟/小时]
     */
    static function getPassedHours($distence)
    {
        $passed = "";
        switch ($distence) {
            case ($distence < 60) : {
                $passed = $distence . "秒";
                break;
            }
            case ($distence > 60 && $distence < 60 * 60) : {
                $passed = intval($distence / 60) . "分钟";
                break;
            }
            case ($distence > 60 * 60) : {
                $passed = sprintf("%.1f", $distence / (60 * 60)) . "小时";
                break;
            }
        }

        return $passed;
    }

    /**
     * 清除危险信息
     *
     * @param mixed $info
     * @return mixed
     */
    static function escapeInfo($info)
    {
        if (is_array($info)) {
            foreach ($info as $key => $value) {
                $info[$key] = escapeInfo($value);
            }
        } else {
            return htmlspecialcharsUni($info);
        }
        return $info;
    }

    /**
     * 针对Unicode不安全改进的安全版htmlspecialchars()
     *
     * @param    string    Text to be made html-safe
     *
     * @return    string
     */
    static function htmlspecialcharsUni($text, $entities = true)
    {
        return str_replace(
        // replace special html characters
            array(
                '<',
                '>',
                '"',
                '\''
            ), array(
            '&lt;',
            '&gt;',
            '&quot;',
            '&apos;'
        ), preg_replace(
        // translates all non-unicode entities
            '/&(?!' . ($entities ? '#[0-9]+|shy' : '(#[0-9]+|[a-z]+)') . ';)/si', '&amp;', $text));
    }

    /**
     * 高级搜索代码
     *
     * @param array $keyword 关键字数组
     * @param string $con 关系，and 或 or
     * @param string $method 模糊或者精确搜索
     * @param array $field 要搜索的字段数组
     * @return string
     */
    static function searchString($keyword, $con, $method, $field)
    {
        $tmp = null;
        $method = strtoupper($method);
        // 搜索中对 "_" 的过滤
        $keyword = str_replace("_", "\\_", trim($keyword));
        $keyword = split("[ \t\r\n,]+", $keyword);
        /*
         * foreach ($field as $k => $v) {
         * }
         */
        $num = count($field);
        if ($con == "OR") {
            $con = "OR";
        } else {
            $con = "AND";
        }
        // 模糊查找
        if ($method == "LIKE") {
            for ($i = 0; $i < $num; $i++) {
                $i < $num - 1 ? $condition = "OR" : $condition = null;
                $tmp .= " {$field[$i]} $method '%" . join("%' $con {$field[$i]} $method '%", $keyword) . "%' $condition";
            }
        } else { // 精确查找
            for ($i = 0; $i < $num; $i++) {
                $i < $num - 1 ? $condition = $con : $condition = null;
                $tmp .= " INSTR({$field[$i]}, \"" . join("\") != 0 $con INSTR({$field[$i]}, \"", $keyword) . "\") != 0 $condition";
            }
        }
        return "(" . $tmp . ")";
    }

    /**
     * 增加了全角转半角的trim
     *
     * @param    string $str 原字符串
     * @return  string  $str    转换后的字符串
     */
    static function wtrim($str)
    {
        return trim(sbc2abc($str));
    }

    /**
     * 全角转半角
     *
     * @param    string $str 原字符串
     * @return  string  $str    转换后的字符串
     */
    static function sbc2abc($str)
    {
        $f = array(
            '　',
            '０',
            '１',
            '２',
            '３',
            '４',
            '５',
            '６',
            '７',
            '８',
            '９',
            'ａ',
            'ｂ',
            'ｃ',
            'ｄ',
            'ｅ',
            'ｆ',
            'ｇ',
            'ｈ',
            'ｉ',
            'ｊ',
            'ｋ',
            'ｌ',
            'ｍ',
            'ｎ',
            'ｏ',
            'ｐ',
            'ｑ',
            'ｒ',
            'ｓ',
            'ｔ',
            'ｕ',
            'ｖ',
            'ｗ',
            'ｘ',
            'ｙ',
            'ｚ',
            'Ａ',
            'Ｂ',
            'Ｃ',
            'Ｄ',
            'Ｅ',
            'Ｆ',
            'Ｇ',
            'Ｈ',
            'Ｉ',
            'Ｊ',
            'Ｋ',
            'Ｌ',
            'Ｍ',
            'Ｎ',
            'Ｏ',
            'Ｐ',
            'Ｑ',
            'Ｒ',
            'Ｓ',
            'Ｔ',
            'Ｕ',
            'Ｖ',
            'Ｗ',
            'Ｘ',
            'Ｙ',
            'Ｚ',
            '．',
            '－',
            '＿',
            '＠'
        );
        $t = array(
            ' ',
            '0',
            '1',
            '2',
            '3',
            '4',
            '5',
            '6',
            '7',
            '8',
            '9',
            'a',
            'b',
            'c',
            'd',
            'e',
            'f',
            'g',
            'h',
            'i',
            'j',
            'k',
            'l',
            'm',
            'n',
            'o',
            'p',
            'q',
            'r',
            's',
            't',
            'u',
            'v',
            'w',
            'x',
            'y',
            'z',
            'A',
            'B',
            'C',
            'D',
            'E',
            'F',
            'G',
            'H',
            'I',
            'J',
            'K',
            'L',
            'M',
            'N',
            'O',
            'P',
            'Q',
            'R',
            'S',
            'T',
            'U',
            'V',
            'W',
            'X',
            'Y',
            'Z',
            '.',
            '-',
            '_',
            '@'
        );
        $str = str_replace($f, $t, $str);
        return $str;
    }


    /*
     * 过滤
     */
    static function removeXSS($str)
    {
        $str = str_replace('<!--  -->', '', $str);
        $str = preg_replace('~/\*[ ]+\*/~i', '', $str);
        $str = preg_replace('/\\\0{0,4}4[0-9a-f]/is', '', $str);
        $str = preg_replace('/\\\0{0,4}5[0-9a]/is', '', $str);
        $str = preg_replace('/\\\0{0,4}6[0-9a-f]/is', '', $str);
        $str = preg_replace('/\\\0{0,4}7[0-9a]/is', '', $str);
        $str = preg_replace('/&#x0{0,8}[0-9a-f]{2};/is', '', $str);
        $str = preg_replace('/&#0{0,8}[0-9]{2,3};/is', '', $str);
        $str = preg_replace('/&#0{0,8}[0-9]{2,3};/is', '', $str);

        $str = htmlspecialchars($str);
        // $str = preg_replace('/&lt;/i', '<', $str);
        // $str = preg_replace('/&gt;/i', '>', $str);

        // 非成对标签
        $lone_tags = array(
            "img",
            "param",
            "br",
            "hr"
        );
        foreach ($lone_tags as $key => $val) {
            $val = preg_quote($val);
            $str = preg_replace('/&lt;' . $val . '(.*)(\/?)&gt;/isU', '<' . $val . "\\1\\2>", $str);
            $str = transCase($str);
            $str = preg_replace_callback('/<' . $val . '(.+?)>/i', create_function('$temp', 'return str_replace("&quot;","\"",$temp[0]);'), $str);
        }
        $str = preg_replace('/&amp;/i', '&', $str);
        // 成对标签
        $double_tags = array(
            "table",
            "tr",
            "td",
            "font",
            "a",
            "object",
            "embed",
            "p",
            "strong",
            "em",
            "u",
            "ol",
            "ul",
            "li",
            "div",
            "tbody",
            "span",
            "blockquote",
            "pre",
            "b",
            "font"
        );
        foreach ($double_tags as $key => $val) {
            $val = preg_quote($val);
            $str = preg_replace('/&lt;' . $val . '(.*)&gt;/isU', '<' . $val . "\\1>", $str);
            $str = transCase($str);
            $str = preg_replace_callback('/<' . $val . '(.+?)>/i', create_function('$temp', 'return str_replace("&quot;","\"",$temp[0]);'), $str);
            $str = preg_replace('/&lt;\/' . $val . '&gt;/is', '</' . $val . ">", $str);
        }
        // 清理js
        $tags = Array(
            'javascript',
            'vbscript',
            'expression',
            'applet',
            'meta',
            'xml',
            'behaviour',
            'blink',
            'link',
            'style',
            'script',
            'embed',
            'object',
            'iframe',
            'frame',
            'frameset',
            'ilayer',
            'layer',
            'bgsound',
            'title',
            'base',
            'font'
        );
        foreach ($tags as $tag) {
            $tag = preg_quote($tag);
            $str = preg_replace('/' . $tag . '\(.*\)/isU', '\\1', $str);
            $str = preg_replace('/' . $tag . '\s*:/isU', $tag . '\:', $str);
        }
        $str = preg_replace('/[\s]+on[\w]+[\s]*=/is', '', $str);
        Return $str;
    }

    static function transCase($str)
    {
        $str = preg_replace('/(e|ｅ|Ｅ)(x|ｘ|Ｘ)(p|ｐ|Ｐ)(r|ｒ|Ｒ)(e|ｅ|Ｅ)(s|ｓ|Ｓ)(s|ｓ|Ｓ)(i|ｉ|Ｉ)(o|ｏ|Ｏ)(n|ｎ|Ｎ)/is', 'expression', $str);
        Return $str;
    }


    /**
     * 得到PHP错误，并报告一个系统错误
     *
     * @param integer $errorNo
     * @param string $message
     * @param string $filename
     * @param integer $lineNo
     */
    static function handleError($errorNo, $message, $filename, $lineNo)
    {
        if (error_reporting() != 0) {
            $type = 'error';
            switch ($errorNo) {
                case 2 :
                    $type = 'warning';
                    break;
                case 8 :
                    $type = 'notice';
                    break;
            }
            throw new Exception('PHP ' . $type . ' in file ' . $filename . ' (' . $lineNo . '): ' . $message, 0);
        }
    }

    // 创建URL
    static function createUrl($uri, $params = null)
    {
        if (is_array($uri)) {
            if (!isset($uri['uri'])) return '';
        } elseif (is_string($uri)) {
            $uri = $uri;
        } else {
            return '';
        }
        $url = (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443') ? 'https://' : 'http://';
        $url .= $_SERVER['HTTP_HOST'];
        $url = trim($url, '/') . '/' . ltrim($uri, '/');
        if (strpos($url, "?")) {
            $url = trim($url, '&') . '&';
        } else {
            $url = trim($url, '?') . '?';
        }
        if (is_array($params)) {
            $url .= http_build_query($params);
        } elseif (is_string($params)) {
            $url .= $params;
        } else {
            $url = trim(trim($url, '?'), '&');
        }
        //$url .= isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : urlencode($_SERVER['PHP_SELF']) . '?' . urlencode($_SERVER['QUERY_STRING']);
        return $url;
    }

    static function smarty_createurl($param, $smarty = null)
    {
        if (!isset($param['uri'])) return '';
        $_ = $param;
        unset($_['uri']);
        return self::createUrl($param['uri'], $_);
    }

    // 当前URl
    static function self_url()
    {
        $url = (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443') ? 'https://' : 'http://';
        $url .= $_SERVER['HTTP_HOST'];
        $url .= isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : urlencode($_SERVER['PHP_SELF']) . '?' . urlencode($_SERVER['QUERY_STRING']);
        return $url;
    }

    // 获得数字大写
    static function get_date_number_chinaese($var)
    {
        $arr = array(
            '日',
            '一',
            '二',
            '三',
            '四',
            '五',
            '六',
        );
        return '周' . $arr[$var];
    }

    /**
     * 简单的订单号hash加解密
     * @param $number_string
     * @param string $type
     * @return string
     */
    static function hash_orderid($number_string, $type = 'encode')
    {
        $rand_array = array(
            '0' => 'a',
            '1' => 'g',
            '2' => 'd',
            '3' => 'o',
            '4' => '0',
            '5' => 'n',
            '6' => '1',
            '7' => '2',
            '8' => 'z',
            '9' => '3',
            'a' => '4',
            'b' => 'k',
            'c' => 'y',
            'd' => 'j',
            'e' => 'f',
            'f' => 'm',
            'g' => 'b',
            'h' => 'x',
            'i' => 'w',
            'j' => '6',
            'k' => '5',
            'l' => 'i',
            'm' => 'c',
            'n' => '7',
            'o' => 'p',
            'p' => '8',
            'q' => 'q',
            'r' => 'h',
            's' => 'e',
            't' => 'r',
            'u' => 't',
            'v' => 'u',
            'w' => 'l',
            'x' => 's',
            'y' => '9',
            'z' => 'v',
        );
        if ($type == 'decode') {
            $rand_array = array_flip($rand_array);
        }
        $string = "$number_string";
        $new_string = '';
        for ($i = 0; $i < strlen($string); $i++) {
            $new_string .= $rand_array["{$string[$i]}"];
        }
        return $new_string;
    }
}
